<?php
$sql="SHOW TABLE STATUS FROM " . MYSQL_DB;
$tables = G::$ds->all($sql);

if ( empty($tables) ) return;
$data = "<?php \n";

foreach( $tables as $table ){

	$tableName = trim($table['Name']);

	$tableName = is_callable('g_table_filter') ? g_table_filter($tableName) : $tableName;
	if ( empty($tableName) ) continue;

	$vars = array();
	$vars['db_name'] = MYSQL_DB;
	$vars['table_class_prefix'] = 'T_';
	
	$tableClassName = G::computed_style_merge($tableName,true,'_');
	$vars['table_class_name'] = $tableClassName;
	$vars['gen_time'] = date('Y-m-d H:i:s',time());
	$vars['table'] = $table;
	
	// 注入表信息
	$columns = G::$ds->all(sprintf('show full columns from %s',$tableName));
	
	// 主键信息
	$prikeys = array();
	foreach($columns as $column){
		if ($column['Key'] == 'PRI'){
			$prikeys[$column['Field']] = 'auto_increment' == $column['Extra'];
		}
	}
	
	$vars['prikeys'] = $prikeys;
	$vars['columns'] = $columns;

	extract($vars);
	ob_start();
?>

/**
 * <?php echo "{$db_name}.{$table['Name']}"; ?><?php echo "\n"; ?>
 * <?php echo $table['Comment']?><?php echo "\n"; ?>
 * <?php echo "\n"; ?>
 * 表创建时间: <?php echo $table['Create_time']; ?><?php echo "\n"; ?>
 * 表更新时间: <?php echo $table['Update_time']; ?><?php echo "\n"; ?>
 *<?php echo "\n"; ?>
 * @author Gent <?php echo $gen_time; ?><?php echo "\n"; ?>
 */<?php echo "\n"; ?>
class <?php echo "{$table_class_prefix}{$table_class_name}" ?> {<?php echo "\n"; ?>
	
	/**<?php echo "\n"; ?>
	 * 数据表名<?php echo "\n"; ?>
	 * <?php echo "\n"; ?>
	 * @var string<?php echo "\n"; ?>
	 */<?php echo "\n"; ?>
	static $_name = '<?php echo $table['Name']; ?>';<?php echo "\n"; ?>
	
	/**<?php echo "\n"; ?>
	 * 数据表主键<?php echo "\n"; ?>
	 * key是主键名,值指是否为auto_increment<?php echo "\n"; ?>
	 * <?php echo "\n"; ?>
	 * @var array<?php echo "\n"; ?>
	 */<?php echo "\n"; ?>
	static $_pkeys = <?php echo empty($prikeys) ? 'NULL' : var_export($prikeys, true); ?>;<?php echo "\n"; ?>
	
	<?php foreach($columns as $column): ?>
/**<?php echo "\n"; ?>
	 * <?php echo empty($column['Comment']) ? "字段名: {$column['Field']}" : $column['Comment']; ?><?php echo "\n"; ?>
	 * <?php echo "\n"; ?>
	 * 允许空值: <?php echo $column['Null']; ?><?php echo "\n"; ?>
	 * 默认值: <?php echo $column['Default']; ?><?php echo "\n"; ?>
	 * <?php echo "\n"; ?>
	 * @var <?php echo $column['Type']; ?><?php echo "\n"; ?>
	 */<?php echo "\n"; ?>
	static $<?php echo strtolower($column['Field']); ?> = '<?php echo $column['Field']; ?>';<?php echo "\n"; ?>
	
	<?php endforeach; ?>
	
}
<?php
	$contents = ob_get_contents();
	ob_end_clean();

	$data .= "{$contents}\n";
}

if ( !defined('TABLE_GEN_FILE') )
{
	die( 'cannot set genfile: (TABLE_GEN_FILE)');
}

@file_put_contents(TABLE_GEN_FILE, $data);

echo "已完成,请查看文件: " . basename(TABLE_GEN_FILE);

?>